<?php
/**
 * 广告
 * User: cxm
 * Date: 2019/10/24
 * Time: 16:06
 */
namespace App\Http\Controllers\Admin\Adv;
use App\Http\Controllers\Admin\Controller;
use App\Models\Adv;
use DB,Validator;
use Illuminate\Http\Request;

class AdvController extends Controller {
    /**
     * 获取广告列表
     * URL GET:/admin/adv/get-lists
     * @param Request $request
     * @param string keyword 广告关键字
     * @param int position_id 广告位
     * @param int status 状态 1可用2不可用
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['keyword','position_id','status','page','limit']);
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $params['where'][] = ['title','like','%'.$keyword.'%'];
        }
        // 广告位
        if (array_key_exists('position_id',$params) && !empty($params['position_id'])) {
            $params['where'][] = ['position_id',$params['position_id']];
        }
        // 状态
        if (array_key_exists('status',$params) && !empty($params['status'])) {
            $params['where'][] = ['status',$params['status']];
        }
        // 广告位
        $params['with'][] = 'position:id,name';
        // 图片
        $params['with'][] = 'file:id,path';
        $data = Adv::listByWhere($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 设置广告可用、不可用
     * URL POST:/admin/adv/enabled
     * @param Request $request
     * @param int adv_id 广告ID
     * @return mixed
     */
    public function enabled(Request $request){
        $params = $request->only(['adv_id']);
        if (!array_key_exists('adv_id',$params) || $params['adv_id'] < 1) {
            return $this->error('缺少广告ID');
        }
        $adv = Adv::find($params['adv_id']);
        if (!$adv) {
            return $this->error('广告不存在');
        }
        $status = ($adv->status == 1) ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['adv_id']];
        $field = ['status'=>$status];
        $data = Adv::modify($where,$field);
        if (!$data) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 广告删除
     * URL POST:/admin/adv/delete
     * @param Request $request
     * @param array ids 广告ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params) || empty($params['ids'])) {
            return $this->error('缺少广告ID');
        }
        $data = Adv::whereIn('id',$params['ids'])->delete();
        if (!$data) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 广告添加、编辑
     * URL POST:/admin/adv/store
     * @param Request $request
     * @param int id 广告ID 编辑时必传
     * @param int position_id 广告位ID
     * @param string title 广告标题
     * @param int type 跳转方式 1链接跳转2参数跳转
     * @param int info_id 跳转参数ID
     * @param int images 图片ID
     * @param string per 链接方式 http|https
     * @param string url 跳转地址
     * @param string start_time 有效期开始时间 不设置则长久有效
     * @param string end_time 有效期结束时间
     * @param int status 状态 1可用2不可用
     * @param int sort 排序
     * @return mixed
     * @throws
     */
    public function store(Request $request){
        $params = $request->only(['id','position_id','title','type','info_id','images','per','url','start_time','end_time','status','sort']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $type = isset($params['type']) ? $params['type'] : 1;
        $per = isset($params['per']) ? $params['per'] : 'http://';
        $validator = Validator::make($params,[
            'position_id'           => ['required','integer','min:1'],
            'title'                 => ['required'],
            //'info_id'               => [($type == 2) ? 'required' : '',($type == 2) ? 'integer':'',($type == 2) ? 'min:1':''],
            'images'                => ['required','integer','min:1'],
            //'url'                   => [($type == 1) ? 'required' : '']
        ],[
            'position_id.required'  => '请选择广告位',
            'position_id.integer'   => '广告位值为正整数',
            'position_id.min'       => '广告位值最小为1',
            'title.required'        => '请输入广告标题',
            //'info_id.required'      => '跳转参数不能为空',
            //'info_id.integer'       => '跳转参数值为正整数',
            //'info_id.min'           => '跳转参数值最小为1',
            'images.required'       => '广告图片不能为空',
            'images.integer'        => '广告图片值为正整数',
            'images.min'            => '广告图片值最小为1',
            //'url.required'          => '跳转地址不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $adv = new Adv();
        }else {
            $adv = Adv::find($id);
            if (!$adv) {
                return $this->error('广告不存在');
            }
        }
        DB::beginTransaction();
        try{
            $adv->position_id           = $params['position_id'];
            $adv->title                 = $params['title'];
            $adv->type                  = $params['type'];
            $adv->info_id               = isset($params['info_id']) ? $params['info_id'] : 0;
            $adv->images                = $params['images'];
            $adv->url                   = isset($params['url']) ? $per.$params['url'] : '';
            if (isset($params['start_time'])) {
                $adv->start_time            =  $params['start_time'];
            }
            if (isset($params['end_time'])) {
                $adv->end_time              = $params['end_time'];
            }
            $adv->sort                  = isset($params['sort'])? $params['sort'] : 1;
            $adv->status                = isset($params['status']) ? $params['status'] : 1;
            $adv->save();
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 修改排序
     * URL POST:/admin/adv/updateSort
     * @param Request $request
     * @param int id 广告ID
     * @param int sort 排序值
     * @return mixed
     */
    public function updateSort(Request $request){
        $params =$request->only(['id','sort']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少主营业务ID');
        }
        $sort = isset($params['sort']) ? $params['sort'] : 1;
        $detail = Adv::find($params['id']);
        if (!$detail) {
            return $this->error('主营业务不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$sort];
        $result = Adv::modify($where,$field);
        if ($result === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }
}